<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 5.1.1">
<meta name="baidu-site-verification" content="code-hkfwkpUecU" />
  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png">
  <link rel="mask-icon" href="/images/logo.svg" color="#222">
  <meta name="baidu-site-verification" content="true">

<link rel="stylesheet" href="/css/main.css">

<link rel="stylesheet" href="//fonts.googleapis.com/css?family=Monda:300,300italic,400,400italic,700,700italic|Roboto+Slab:300,300italic,400,400italic,700,700italic|PT+Mono:300,300italic,400,400italic,700,700italic&display=swap&subset=latin,latin-ext">

<link rel="stylesheet" href="//cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free@5.14.0/css/all.min.css">
  <link rel="stylesheet" href="//cdn.jsdelivr.net/npm/animate.css@3.1.1/animate.min.css">

<script class="hexo-configurations">
    var NexT = window.NexT || {};
    var CONFIG = {"hostname":"github.com","root":"/","scheme":"Gemini","version":"8.0.0","exturl":false,"sidebar":{"position":"left","display":"post","padding":18,"offset":12},"copycode":true,"bookmark":{"enable":false,"color":"#222","save":"auto"},"fancybox":false,"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":"disqus","storage":true,"lazyload":false,"nav":null},"motion":{"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"fadeInDown","post_body":"fadeInDown","coll_header":"fadeInLeft","sidebar":"fadeInUp"}},"prism":false,"i18n":{"placeholder":"搜索...","empty":"没有找到任何搜索结果：${query}","hits_time":"找到 ${hits} 个搜索结果（用时 ${time} 毫秒）","hits":"找到 ${hits} 个搜索结果"},"path":"search.xml","localsearch":{"enable":true,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false}};
  </script>

  <meta name="description" content="模块 如果从python 解释器退出并再次进入，那么之前定义的函数和变量都会丢失，因此，如果想编写一个稍微长一些的程序，最好使用功能文本编辑器（如pycharm) 为解释器准备输入并将该文件作为输入运行，这被称为编写 脚本  为了将程序拆分为几个文件以方便维护，并且希望在不同程序中使用同一个函数而不是把和这个函数复制到每一个程序中去，可以使用 python提供的模块。  模块可以把定义放在一个文件">
<meta property="og:type" content="article">
<meta property="og:title" content="模块">
<meta property="og:url" content="https://github.com/shanlu123/2020/09/27/python/%E6%A8%A1%E5%9D%97/index.html">
<meta property="og:site_name" content="shanlu的博客">
<meta property="og:description" content="模块 如果从python 解释器退出并再次进入，那么之前定义的函数和变量都会丢失，因此，如果想编写一个稍微长一些的程序，最好使用功能文本编辑器（如pycharm) 为解释器准备输入并将该文件作为输入运行，这被称为编写 脚本  为了将程序拆分为几个文件以方便维护，并且希望在不同程序中使用同一个函数而不是把和这个函数复制到每一个程序中去，可以使用 python提供的模块。  模块可以把定义放在一个文件">
<meta property="og:locale" content="zh_CN">
<meta property="article:published_time" content="2020-09-26T16:00:00.000Z">
<meta property="article:modified_time" content="2020-10-04T09:03:26.216Z">
<meta property="article:author" content="shanlu">
<meta property="article:tag" content="python">
<meta name="twitter:card" content="summary">


<link rel="canonical" href="https://github.com/shanlu123/2020/09/27/python/%E6%A8%A1%E5%9D%97/">


<script class="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome : false,
    isPost : true,
    lang   : 'zh-CN'
  };
</script>

  <title>模块 | shanlu的博客</title>
  






  <noscript>
  <style>
  body { margin-top: 2rem; }

  .use-motion .menu-item,
  .use-motion .sidebar,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header {
    visibility: visible;
  }

  .use-motion .header,
  .use-motion .site-brand-container .toggle,
  .use-motion .footer { opacity: initial; }

  .use-motion .site-title,
  .use-motion .site-subtitle,
  .use-motion .custom-logo-image {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line {
    transform: scaleX(1);
  }

  .search-pop-overlay, .sidebar-nav { display: none; }
  .sidebar-panel { display: block; }
  </style>
</noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage" class="use-motion">
  <div class="headband"></div>
  <a href="https://github.com/shanlu123" class="github-corner" aria-label="View source on GitHub"><svg width="80" height="80" viewBox="0 0 250 250" style="fill:#151513; color:#fff; position: absolute; top: 0; border: 0; right: 0;" aria-hidden="true"><path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"></path><path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2" fill="currentColor" style="transform-origin: 130px 106px;" class="octo-arm"></path><path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z" fill="currentColor" class="octo-body"></path></svg></a><style>.github-corner:hover .octo-arm{animation:octocat-wave 560ms ease-in-out}@keyframes octocat-wave{0%,100%{transform:rotate(0)}20%,60%{transform:rotate(-25deg)}40%,80%{transform:rotate(10deg)}}@media (max-width:500px){.github-corner:hover .octo-arm{animation:none}.github-corner .octo-arm{animation:octocat-wave 560ms ease-in-out}}</style>

  <main class="main">
    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏">
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/" class="brand" rel="start">
      <i class="logo-line"></i>
      <h1 class="site-title">shanlu的博客</h1>
      <i class="logo-line"></i>
    </a>
      <p class="site-subtitle" itemprop="description">三餐四季，冷暖自知</p>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
        <i class="fa fa-search fa-fw fa-lg"></i>
    </div>
  </div>
</div>



<nav class="site-nav">
  <ul class="main-menu menu">
        <li class="menu-item menu-item-home">

    <a href="/home" rel="section"><i class="fa fa-home fa-fw"></i>首页</a>

  </li>
        <li class="menu-item menu-item-tags">

    <a href="/tags/" rel="section"><i class="fa fa-tags fa-fw"></i>标签</a>

  </li>
        <li class="menu-item menu-item-categories">

    <a href="/categories/" rel="section"><i class="fa fa-th fa-fw"></i>分类</a>

  </li>
        <li class="menu-item menu-item-前端">

    <a href="/%E5%89%8D%E7%AB%AF/" rel="section"><i class="fa fa-cloud fa-fw"></i>前端</a>

  </li>
        <li class="menu-item menu-item-生活">

    <a href="/%E7%94%9F%E6%B4%BB/" rel="section"><i class="fa fa-user fa-fw"></i>生活</a>

  </li>
        <li class="menu-item menu-item-school">

    <a href="/school/" rel="section"><i class="fa fa-graduation-cap fa-fw"></i>学校</a>

  </li>
        <li class="menu-item menu-item-tree_hole">

    <a href="/tree_hole/" rel="section"><i class="fa fa-tree fa-fw"></i>树洞</a>

  </li>
        <li class="menu-item menu-item-photos">

    <a href="/photos/" rel="section"><i class="fa fa-camera fa-fw"></i>相册</a>

  </li>
        <li class="menu-item menu-item-archives">

    <a href="/archives/" rel="section"><i class="fa fa-archive fa-fw"></i>归档</a>

  </li>
      <li class="menu-item menu-item-search">
        <a role="button" class="popup-trigger"><i class="fa fa-search fa-fw"></i>搜索
        </a>
      </li>
  </ul>
</nav>



  <div class="search-pop-overlay">
    <div class="popup search-popup">
        <div class="search-header">
  <span class="search-icon">
    <i class="fa fa-search"></i>
  </span>
  <div class="search-input-container">
    <input autocomplete="off" autocapitalize="off" maxlength="80"
           placeholder="搜索..." spellcheck="false"
           type="search" class="search-input">
  </div>
  <span class="popup-btn-close">
    <i class="fa fa-times-circle"></i>
  </span>
</div>
<div class="search-result-container no-result">
  <div class="search-result-icon">
    <i class="fa fa-spinner fa-pulse fa-5x"></i>
  </div>
</div>

    </div>
  </div>

</div>
        
  
  <div class="toggle sidebar-toggle">
    <span class="toggle-line"></span>
    <span class="toggle-line"></span>
    <span class="toggle-line"></span>
  </div>

  <aside class="sidebar">

    <div class="sidebar-inner sidebar-nav-active sidebar-toc-active">
      <ul class="sidebar-nav">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <!--noindex-->
      <section class="post-toc-wrap sidebar-panel">
          <div class="post-toc animated"><ol class="nav"><li class="nav-item nav-level-3"><a class="nav-link" href="#%E6%A8%A1%E5%9D%97"><span class="nav-number">1.</span> <span class="nav-text">模块</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E6%A0%87%E5%87%86%E6%A8%A1%E5%9D%97"><span class="nav-number">2.</span> <span class="nav-text">标准模块</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#dir-%E5%87%BD%E6%95%B0"><span class="nav-number">3.</span> <span class="nav-text">dir() 函数</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E5%8C%85"><span class="nav-number">4.</span> <span class="nav-text">包</span></a></li></ol></div>
      </section>
      <!--/noindex-->

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-author animated" itemprop="author" itemscope itemtype="http://schema.org/Person">
    <img class="site-author-image" itemprop="image" alt="shanlu"
      src="/images/avatar.jpg">
  <p class="site-author-name" itemprop="name">shanlu</p>
  <div class="site-description" itemprop="description"></div>
</div>
<div class="site-state-wrap animated">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
          <a href="/archives/">
        
          <span class="site-state-item-count">127</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
            <a href="/categories/">
          
        <span class="site-state-item-count">11</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
      <div class="site-state-item site-state-tags">
            <a href="/tags/">
          
        <span class="site-state-item-count">11</span>
        <span class="site-state-item-name">标签</span></a>
      </div>
  </nav>
</div>
  <div class="links-of-author animated">
      <span class="links-of-author-item">
        <a href="https://github.com/shanlu123" title="GitHub → https:&#x2F;&#x2F;github.com&#x2F;shanlu123"><i class="fab fa-github fa-fw"></i>GitHub</a>
      </span>
      <span class="links-of-author-item">
        <a href="https://www.cnblogs.com/shanlu0000/p/11478994.html" title="博客园 → https:&#x2F;&#x2F;www.cnblogs.com&#x2F;shanlu0000&#x2F;p&#x2F;11478994.html" rel="noopener" target="_blank"><i class="fa fa-blog fa-fw"></i>博客园</a>
      </span>
      <span class="links-of-author-item">
        <a href="mailto:yourname@gmail.com" title="E-Mail → mailto:yourname@gmail.com" rel="noopener" target="_blank"><i class="fa fa-envelope fa-fw"></i>E-Mail</a>
      </span>
      <span class="links-of-author-item">
        <a href="https://weibo.com/u/6662419816/home?wvr=5" title="微博 → https:&#x2F;&#x2F;weibo.com&#x2F;u&#x2F;6662419816&#x2F;home?wvr&#x3D;5" rel="noopener" target="_blank"><i class="fab fa-weibo fa-fw"></i>微博</a>
      </span>
  </div>


  <div class="links-of-blogroll animated">
    <div class="links-of-blogroll-title"><i class="fa fa-globe fa-fw"></i>
      友情链接
    </div>
    <ul class="links-of-blogroll-list">
        <li class="links-of-blogroll-item">
          <a href="https://www.npmjs.com/" title="https:&#x2F;&#x2F;www.npmjs.com&#x2F;" rel="noopener" target="_blank">npm</a>
        </li>
        <li class="links-of-blogroll-item">
          <a href="https://www.bilibili.com/" title="https:&#x2F;&#x2F;www.bilibili.com&#x2F;" rel="noopener" target="_blank">bilibili</a>
        </li>
        <li class="links-of-blogroll-item">
          <a href="https://stackoverflow.com/" title="https:&#x2F;&#x2F;stackoverflow.com&#x2F;" rel="noopener" target="_blank">stackoverflow</a>
        </li>
        <li class="links-of-blogroll-item">
          <a href="https://developers.weixin.qq.com/miniprogram/dev/component/" title="https:&#x2F;&#x2F;developers.weixin.qq.com&#x2F;miniprogram&#x2F;dev&#x2F;component&#x2F;" rel="noopener" target="_blank">小程序</a>
        </li>
        <li class="links-of-blogroll-item">
          <a href="http://www.ruanyifeng.com/blog/" title="http:&#x2F;&#x2F;www.ruanyifeng.com&#x2F;blog&#x2F;" rel="noopener" target="_blank">阮一峰</a>
        </li>
        <li class="links-of-blogroll-item">
          <a href="https://cn.aliyun.com/" title="https:&#x2F;&#x2F;cn.aliyun.com&#x2F;" rel="noopener" target="_blank">阿里云</a>
        </li>
    </ul>
  </div>

      </section>
    </div>
  </aside>
  <div class="sidebar-dimmer"></div>


    </header>

    
  <div class="back-to-top">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>

<noscript>
  <div class="noscript-warning">Theme NexT works best with JavaScript enabled</div>
</noscript>


    <div class="main-inner post posts-expand">
      

      

    
  
  

  <article itemscope itemtype="http://schema.org/Article" class="post-block" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="https://github.com/shanlu123/2020/09/27/python/%E6%A8%A1%E5%9D%97/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/avatar.jpg">
      <meta itemprop="name" content="shanlu">
      <meta itemprop="description" content="">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="shanlu的博客">
    </span>

    
    
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          模块
        </h1>

        <div class="post-meta-container">
          <div class="post-meta">
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-calendar"></i>
      </span>
      <span class="post-meta-item-text">发表于</span>

      <time title="创建时间：2020-09-27 00:00:00" itemprop="dateCreated datePublished" datetime="2020-09-27T00:00:00+08:00">2020-09-27</time>
    </span>
      <span class="post-meta-item">
        <span class="post-meta-item-icon">
          <i class="far fa-calendar-check"></i>
        </span>
        <span class="post-meta-item-text">更新于</span>
        <time title="修改时间：2020-10-04 17:03:26" itemprop="dateModified" datetime="2020-10-04T17:03:26+08:00">2020-10-04</time>
      </span>
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-folder"></i>
      </span>
      <span class="post-meta-item-text">分类于</span>
        <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
          <a href="/categories/python/" itemprop="url" rel="index"><span itemprop="name">python</span></a>
        </span>
    </span>

  
    <span id="/2020/09/27/python/%E6%A8%A1%E5%9D%97/" class="post-meta-item leancloud_visitors" data-flag-title="模块" title="阅读次数">
      <span class="post-meta-item-icon">
        <i class="far fa-eye"></i>
      </span>
      <span class="post-meta-item-text">阅读次数：</span>
      <span class="leancloud-visitors-count"></span>
    </span>
    <span class="post-meta-item" title="阅读次数" id="busuanzi_container_page_pv" style="display: none;">
      <span class="post-meta-item-icon">
        <i class="far fa-eye"></i>
      </span>
      <span class="post-meta-item-text">阅读次数：</span>
      <span id="busuanzi_value_page_pv"></span>
    </span>
  
  <span class="post-meta-item">
    
      <span class="post-meta-item-icon">
        <i class="far fa-comment"></i>
      </span>
      <span class="post-meta-item-text">Valine：</span>
    
    <a title="valine" href="/2020/09/27/python/%E6%A8%A1%E5%9D%97/#valine-comments" itemprop="discussionUrl">
      <span class="post-comments-count valine-comment-count" data-xid="/2020/09/27/python/%E6%A8%A1%E5%9D%97/" itemprop="commentCount"></span>
    </a>
  </span>
  
  
    <span class="post-meta-item" title="本文字数">
      <span class="post-meta-item-icon">
        <i class="far fa-file-word"></i>
      </span>
      <span class="post-meta-item-text">本文字数：</span>
      <span>4k</span>
    </span>
    <span class="post-meta-item" title="阅读时长">
      <span class="post-meta-item-icon">
        <i class="far fa-clock"></i>
      </span>
      <span class="post-meta-item-text">阅读时长 &asymp;</span>
      <span>4 分钟</span>
    </span>
</div>

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">
        <h3 id="模块"><a href="#模块" class="headerlink" title="模块"></a>模块</h3><ol>
<li><p>如果从python 解释器退出并再次进入，那么之前定义的函数和变量都会丢失，因此，如果想编写一个稍微长一些的程序，最好使用功能文本编辑器（如pycharm) 为解释器准备输入并将该文件作为输入运行，这被称为编写 脚本</p>
</li>
<li><p>为了将程序拆分为几个文件以方便维护，并且希望在不同程序中使用同一个函数而不是把和这个函数复制到每一个程序中去，可以使用 python提供的模块。</p>
</li>
<li><p>模块可以把定义放在一个文件中，并在脚本或解释器的交互式实例中使用它们， 模块中的定义可以导入到其他模块或者主模块（顶级和计算器模式下执行的脚本中可以访问的变量集合）中</p>
</li>
<li><p>在一个模块中引入外部模块</p>
<ul>
<li>import  模块名 </li>
<li>import  模块名   as  模块别名</li>
<li>也可以只引入模块中的部分内容，from 模块名 import  …….</li>
<li>可以引入同一个模块多次，但是模块的实例只会创建一次</li>
<li>import  可以在程序的任意位置调用，一般写在程序开头</li>
<li>在一个模块内部，模块名可以通过全局变量” _ name _”的值获得，__  name __ 属性值为 __ main __ 的模块是主模块，一个程序中只会有一个主模块</li>
</ul>
</li>
<li><p>例如：</p>
<blockquote>
<p>a.py</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">sum</span>(<span class="params">a, b</span>):</span></span><br><span class="line">    <span class="keyword">return</span> a + b</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">cut</span>(<span class="params">a, b</span>):</span></span><br><span class="line">    <span class="keyword">return</span> a - b</span><br><span class="line"></span><br></pre></td></tr></table></figure>
</blockquote>
<blockquote>
<p>然后在该目录中进入python解释器，导入该模块</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&gt;&gt;&gt; </span>imnport a</span><br></pre></td></tr></table></figure>
</blockquote>
<blockquote>
<p>在当前的符号表中，这并不会直接进入到定义在 a 函数内的名称，只是进入到该模块名中  a 中，可以用模块名访问 sum 和 cut 函数</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&gt;&gt;&gt; </span>a.sum(<span class="number">1</span>,<span class="number">2</span>)</span><br><span class="line"><span class="number">3</span></span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>a.cut(<span class="number">10</span>,<span class="number">4</span>)</span><br><span class="line"><span class="number">6</span></span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>a.__name__</span><br><span class="line"><span class="string">&#x27;a&#x27;</span></span><br><span class="line">&gt;&gt;&gt;</span><br></pre></td></tr></table></figure>
</blockquote>
</li>
<li><p>模块可以包含可执行的语句以及函数定义，这些语句用于初始化模块，它们仅在模块第一次 import  时才执行</p>
</li>
<li><p>每个模块都有它自己的私有符号表，该表用作模块中定义的所有函数的全局符号表。因此，模块的作者可以在模块内使用全局变量而不必担心与用户的全局变量发生冲突。</p>
</li>
<li><p>模块可以导入其他模块，习惯上把所有 import 语句放在模块或脚本的开头，但不要求。被导入的模块名存放在调入模块的全局符号表中</p>
</li>
<li><p>import 语句有一个变体，可以把名字从一个被调模块内直接导入到现模块的符号表里，</p>
<blockquote>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&gt;&gt;&gt; </span><span class="keyword">from</span> a <span class="keyword">import</span> sum,cut</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>sum(<span class="number">1</span>,<span class="number">1</span>)</span><br><span class="line"><span class="number">2</span></span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>cut(<span class="number">3</span>,<span class="number">4</span>)</span><br><span class="line"><span class="number">-1</span></span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>a.__name__</span><br><span class="line">Traceback (most recent call last):</span><br><span class="line">  File <span class="string">&quot;&lt;stdin&gt;&quot;</span>, line <span class="number">1</span>, <span class="keyword">in</span> &lt;module&gt;</span><br><span class="line">NameError: name <span class="string">&#x27;a&#x27;</span> <span class="keyword">is</span> <span class="keyword">not</span> defined</span><br><span class="line">&gt;&gt;&gt;</span><br></pre></td></tr></table></figure>

<p>这并不会把被调入模块名引入到局部变量里，即这么做 a 是未定义的</p>
</blockquote>
</li>
<li><p>还有一个变体甚至可以导入模块内定义的所有名称</p>
<blockquote>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&gt;&gt;&gt; </span><span class="keyword">from</span> a  <span class="keyword">import</span> *</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>sum(<span class="number">1</span>,<span class="number">2</span>)</span><br><span class="line"><span class="number">3</span></span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>a.__name__</span><br><span class="line">Traceback (most recent call last):</span><br><span class="line">  File <span class="string">&quot;&lt;stdin&gt;&quot;</span>, line <span class="number">1</span>, <span class="keyword">in</span> &lt;module&gt;</span><br><span class="line">NameError: name <span class="string">&#x27;a&#x27;</span> <span class="keyword">is</span> <span class="keyword">not</span> defined</span><br></pre></td></tr></table></figure>

<p>这会调入所有不是以下划线(_)开头的名称，在多数情况下，这个功能并不常用，因为会导致代码可读性很差。</p>
</blockquote>
</li>
<li><p>如果模块名称之后带有 as ，在跟在 as 之后的名称将直接绑定到所导入的模块</p>
<blockquote>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&gt;&gt;&gt; </span><span class="keyword">import</span> a <span class="keyword">as</span> module_a</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>module_a.sum(<span class="number">1</span>,<span class="number">3</span>)</span><br><span class="line"><span class="number">4</span></span><br></pre></td></tr></table></figure>

<p>这种方式也可以在用到 from 的时候使用</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&gt;&gt;&gt; </span><span class="keyword">from</span> a <span class="keyword">import</span> sum <span class="keyword">as</span> function_sum</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>function_sum(<span class="number">3</span>,<span class="number">4</span>)</span><br><span class="line"><span class="number">7</span></span><br></pre></td></tr></table></figure>
</blockquote>
</li>
</ol>
<ol start="12">
<li><p>以脚本的方式执行模块</p>
<blockquote>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&gt;&gt;&gt; </span>python a.py &lt;arguments&gt;</span><br></pre></td></tr></table></figure>

<p>模块里的代码会被执行，就像导入了模块一样，但是__ name __ 被赋值为“ __ main __”</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&gt;&gt;&gt; </span>__name__</span><br><span class="line"><span class="string">&#x27;__main__&#x27;</span></span><br></pre></td></tr></table></figure>

<p>这经常用于为模块提供一个方便的用户接口，或用于测试（以脚本的方式运行模块从而执行一些测试套件）</p>
</blockquote>
</li>
<li><p>模块搜索路径</p>
<blockquote>
<p>当一个名为 spam 的模块被导入的时候，解释器首先寻找具有该名称的内置模块。</p>
<p>如果没找到，然后解释器从 sys.path 变量给出的目录列表中寻找名为 spam.py的文件，sys.path 初始有以下目录地址:</p>
<p>​        包含输入脚本的目录，或者未指定文件时的当前目录</p>
<p>​        PYTHONPATH—–一个包含目录名称的列表，它和 shell 变量 PAHT有一样的语法</p>
<p>​        取决于安装的默认的配置</p>
<p>在初始化后，Python程序可以更改 sys.path，包含正在运行脚本的文件目录被放在搜索路径的开头处，标准库路径之前。这意味着将加载此目录里的脚本，而不是标准库中的同名模块。</p>
</blockquote>
</li>
<li><p>“编译过的” python 文件</p>
<blockquote>
<p>为了加速模块载入，Python在 <em>pycache</em> 目录里缓存了每个模块的编译后版本，名称为 moudle.version.pyc，其中名称中的版本字段对编译文件的格式进行编码，一般使用Python版本号。</p>
<p>例如，在CPython3.3中，spam.py的编译版本将被缓存为 _ pycache _/spam.cpython-33.pyc</p>
<p>python在两种情况下不会检查缓存，一是从命令行直接载入的模块，它都是重新编译不存储编译结果；其次，如果没有源模块，它不会检查缓存。</p>
</blockquote>
</li>
</ol>
<h3 id="标准模块"><a href="#标准模块" class="headerlink" title="标准模块"></a>标准模块</h3><ol>
<li><p>python附带了一个标准模块库</p>
</li>
<li><p>一些模块内置于解释器中，它们提供对不属于语言核心但仍然内置的操作的访问，以提高效率或提供对系统调用等操作系统原语的访问</p>
</li>
<li><p>这些模块的集合是一个配置选项，也取决于底层平台，例如，winreg 模块只在 windows 操作系统上提供</p>
</li>
<li><p>特别注意 sys 模块，它被内嵌到每一个Python解释器中，使我们可以获取到python解释器的信息或者通过函数来操作python解释器，变量 sys.psl 和 sys.ps2 定义用作主要和辅助提示的字符串</p>
<blockquote>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&gt;&gt;&gt; </span><span class="keyword">import</span> sys</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>sys.ps1</span><br><span class="line"><span class="string">&#x27;&gt;&gt;&gt; &#x27;</span></span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>sys.ps2</span><br><span class="line"><span class="string">&#x27;... &#x27;</span></span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>sys.ps1=<span class="string">&#x27;C&gt;&#x27;</span></span><br><span class="line">C&gt;print(<span class="string">&#x27;Hello&#x27;</span>)</span><br><span class="line">Hello</span><br><span class="line">C&gt;</span><br></pre></td></tr></table></figure>

<p>这两个变量只有在编译器是交互模式下才被定义</p>
</blockquote>
</li>
<li><p>sys.argv，获取执行代码时，命令行中所包含的参数，返回一个列表，列表中保存了当前命令的所有参数</p>
</li>
<li><p>sys.modules，获取当前程序中引入的所有模块，返回一个字典，字典的 key 是模块的名字，字典的 value 是模块对象</p>
</li>
<li><p>syp.path 变量是一个字符串列表，用于确定解释器的模块搜索路径，该变量被初始化为从环境变量 PYTHONPATH获取的默认路径，或者如果PYTHONPATH未设置，则从内置默认路径初始化。</p>
</li>
<li><p>sys.platform，表示当前python运行的平台，windows平台下，值为 win32</p>
</li>
<li><p>sys.exit() 用来退出程序，参数中可以添加退出提示</p>
</li>
<li><p>pprint 模块给我们提供了一个方法 pprint() ，该方法可以用来对打印的数据做简单的格式化</p>
</li>
<li><p>os 模块可以对操作系统进行访问，os.environ，通过这个属性可以获取到系统的环境变量；os.system，可以用来执行操作系统的名字；</p>
</li>
</ol>
<h3 id="dir-函数"><a href="#dir-函数" class="headerlink" title="dir() 函数"></a>dir() 函数</h3><ol>
<li>内置dir() 函数用于查找模块定义的名称，它返回一个排序过的字符串列表</li>
</ol>
<blockquote>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&gt;&gt;&gt; </span><span class="keyword">import</span> a</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>dir(a)</span><br><span class="line">[<span class="string">&#x27;__builtins__&#x27;</span>, <span class="string">&#x27;__cached__&#x27;</span>, <span class="string">&#x27;__doc__&#x27;</span>, <span class="string">&#x27;__file__&#x27;</span>, <span class="string">&#x27;__loader__&#x27;</span>, <span class="string">&#x27;__name__&#x27;</span>, <span class="string">&#x27;__package__&#x27;</span>, <span class="string">&#x27;__spec__&#x27;</span>, <span class="string">&#x27;cut&#x27;</span>, <span class="string">&#x27;sum&#x27;</span>]</span><br><span class="line">&gt;&gt;&gt;</span><br><span class="line"></span><br><span class="line"><span class="comment">#没有传入参数，dir() 列出你当前定义的名称</span></span><br></pre></td></tr></table></figure>
</blockquote>
<ol start="2">
<li><p>它列出所有类型的名称：变量，模块，函数，等等</p>
</li>
<li><p>不会列出内置函数和变量的名称，它们的定义是在标准模块 builtins 中</p>
</li>
</ol>
<h3 id="包"><a href="#包" class="headerlink" title="包"></a>包</h3><ol>
<li><p>包也是一个模块，当模块中的代码过多时，或者一个模块需要被分解为多个模块时，就需要使用包</p>
</li>
<li><p>包是一种通过用“带点号的模块名”来构造Python模块命名空间的方法，例如，模块名A.B表示A包中名为B的子模块</p>
</li>
<li><p>普通的模块就是一个 py 文件，而包是一个文件夹</p>
</li>
<li><p>包中必须有一个 __ init __.py 文件，这个文件可以包含包中的主要内容</p>
</li>
<li><p>__ pycache __ 是模块的缓存文件，py代码在执行前，需要被解释器先转换为机器码再执行，所以在使用包模块）时，也需要将模块的代码先转换为机器码，而为了提高程序执行的性能，python会在编译过一些之后，将代码保存到一个缓存文件中，这样下次加载这个包（模块）时，就不用重新编译而直接加载缓存中编译好的代码即可。</p>
<blockquote>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">from</span> test <span class="keyword">import</span> a, b</span><br><span class="line"></span><br><span class="line">print(a.c)  <span class="comment"># 30</span></span><br><span class="line">print(b.d)  <span class="comment"># 40</span></span><br></pre></td></tr></table></figure>
</blockquote>
<blockquote>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">test 目录中</span><br><span class="line">a.py</span><br><span class="line">c=<span class="number">30</span></span><br><span class="line"></span><br><span class="line">b.py</span><br><span class="line">d=<span class="number">40</span></span><br></pre></td></tr></table></figure>
</blockquote>
</li>
</ol>

    </div>

    
    
    

    
      <div>
       <div>
  
    <div style="text-align:center;color:#bfbfbf;font-size:16px;">
      <span>-------- 本文结束 </span>
      <i class="fa fa-snowflake-o"></i>
      <span> 感谢阅读 --------</span>
    </div>
  
</div>
      </div>
    

    <footer class="post-footer">
          <div class="reward-container">
  <div></div>
  <button onclick="document.querySelector('.post-reward').classList.toggle('active');">
    赞赏
  </button>
  <div class="post-reward">
      <div>
        <img src="/images/wechatpay.png" alt="shanlu 微信">
        <span>微信</span>
      </div>

  </div>
</div>

          <div class="post-tags">
              <a href="/tags/python/" rel="tag"><i class="fa fa-tag"></i> python</a>
          </div>

        

          <div class="post-nav">
            <div class="post-nav-item">
                <a href="/2020/09/27/python/%E6%95%B0%E6%8D%AE%E7%BB%93%E6%9E%84/" rel="prev" title="数据结构">
                  <i class="fa fa-chevron-left"></i> 数据结构
                </a>
            </div>
            <div class="post-nav-item">
                <a href="/2020/09/28/python/%E8%BE%93%E5%85%A5%E8%BE%93%E5%87%BA/" rel="next" title="输入输出">
                  输入输出 <i class="fa fa-chevron-right"></i>
                </a>
            </div>
          </div>
    </footer>
  </article>
  
  
  



      
    <div class="comments" id="valine-comments"></div>

<script>
  window.addEventListener('tabs:register', () => {
    let { activeClass } = CONFIG.comments;
    if (CONFIG.comments.storage) {
      activeClass = localStorage.getItem('comments_active') || activeClass;
    }
    if (activeClass) {
      const activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
      if (activeTab) {
        activeTab.click();
      }
    }
  });
  if (CONFIG.comments.storage) {
    window.addEventListener('tabs:click', event => {
      if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
      const commentClass = event.target.classList[1];
      localStorage.setItem('comments_active', commentClass);
    });
  }
</script>

    </div>
  </main>

  <footer class="footer">
    <div class="footer-inner">
      

      

<div class="copyright">
  
  &copy; 
  <span itemprop="copyrightYear">2021</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">shanlu</span>
</div>
<div class="wordcount">
  <span class="post-meta-item">
    <span class="post-meta-item-icon">
      <i class="fa fa-chart-line"></i>
    </span>
    <span title="站点总字数">225k</span>
  </span>
  <span class="post-meta-item">
    <span class="post-meta-item-icon">
      <i class="fa fa-coffee"></i>
    </span>
    <span title="站点阅读时长">3:25</span>
  </span>
</div>
<div class="busuanzi-count">
    <span class="post-meta-item" id="busuanzi_container_site_uv" style="display: none;">
      <span class="post-meta-item-icon">
        <i class="fa fa-user"></i>
      </span>
      <span class="site-uv" title="总访客量">
        <span id="busuanzi_value_site_uv"></span>
      </span>
    </span>
    <span class="post-meta-item" id="busuanzi_container_site_pv" style="display: none;">
      <span class="post-meta-item-icon">
        <i class="fa fa-eye"></i>
      </span>
      <span class="site-pv" title="总访问量">
        <span id="busuanzi_value_site_pv"></span>
      </span>
    </span>
</div>
  <div class="powered-by">由 <a href="https://hexo.io/" class="theme-link" rel="noopener" target="_blank">Hexo</a> & <a href="https://theme-next.js.org/" class="theme-link" rel="noopener" target="_blank">NexT.Gemini</a> 强力驱动
  </div>


    <script async src="//dn-lbstatics.qbox.me/busuanzi/2.3/busuanzi.pure.mini.js"></script>

    </div>
  </footer>

  
  <script size="300" alpha="0.6" zIndex="-1" src="//cdn.jsdelivr.net/npm/ribbon.js@1.0.2/dist/ribbon.min.js"></script>
  <script src="//cdn.jsdelivr.net/npm/animejs@3.2.0/lib/anime.min.js"></script>
<script src="/js/utils.js"></script><script src="/js/motion.js"></script><script src="/js/next-boot.js"></script>

  
  <script>
    (function(){
      var bp = document.createElement('script');
      var curProtocol = window.location.protocol.split(':')[0];
      bp.src = (curProtocol === 'https') ? 'https://zz.bdstatic.com/linksubmit/push.js' : 'http://push.zhanzhang.baidu.com/push.js';
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(bp, s);
    })();
  </script>




  <script src="/js/local-search.js"></script>















  
  <script async src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>








  

  
<script>
NexT.utils.loadComments('#valine-comments', () => {
  NexT.utils.getScript('//cdn.jsdelivr.net/npm/valine@1.4.14/dist/Valine.min.js', () => {
    new Valine(Object.assign({
      el  : '#valine-comments',
      path: "/2020/09/27/python/%E6%A8%A1%E5%9D%97/",
    }, {"enable":true,"appId":"M0TTE46ti90I3BUUJqD5WYyD-gzGzoHsz","appKey":"UelegRsJXosPYDakAbUdO5e8","notify":true,"verify":false,"placeholder":"留下评论吧","avatar":"mm","meta":["nick","mail","link"],"pageSize":10,"lang":"zh-cn","visitor":true,"comment_count":true,"recordIP":false,"serverURLs":null,"enableQQ":false,"requiredFields":[]}
    ));
  }, window.Valine);
});
</script>

<script src="/live2dw/lib/L2Dwidget.min.js?094cbace49a39548bed64abff5988b05"></script><script>L2Dwidget.init({"pluginRootPath":"live2dw/","pluginJsPath":"lib/","pluginModelPath":"assets/","tagMode":false,"debug":false,"model":{"jsonPath":"/live2dw/assets/shizuku.model.json"},"display":{"position":"left","width":225,"height":450},"mobile":{"show":true},"react":{"opacity":0.7},"log":false});</script></body>
</html>
